<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数:{{ total }}条</span>
        </template>
        <template #right>
          <el-button
            type="warning"
            size="small"
          >excel导入</el-button>
          <el-button
            type="danger"
            size="small"
            @click="exportToExcel"
          >excel导出</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="userList">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width:100%">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ formatHireType(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="doDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2,4,6,8]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        @close="doClose"
      >
        <MyDialog
          ref="myDialog"
          @close="doAdd"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { delUser, getEmployeeList } from '@/api/employees'
import MyDialog from './MyDialog.vue'
import employees from '@/constant/employees'
const hireType = employees.hireType.reduce((prev, item) => {
  prev[item.id] = item.value
  return prev
}, {})
export default {
  components: {
    MyDialog
  },
  data() {
    return {
      page: 1,
      size: 2,
      total: 0,
      userList: [],
      showDialog: false
    }
  },
  created() {
    this.loadUserList()
  },
  methods: {
    // 查看
    doEdit() {

    },
    exportToExcel() {
      // 1. 发送请求获取导出数据
      // 这里在页面渲染阶段，已经发送过请求，数据存在了this.list中
      // 2. 将数据格式成excel需要的格式
      const { tHeader, result } = this.formatToExcel(this.userList)
      console.log(tHeader, result)
      import('@/vendor/Export2Excel').then(excel => {
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data: result,
          filename: '',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    // 格式化excel数据格式
    formatToExcel(userList) {
      //    中引文的映射对象
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      // tHeader = ['编号','密码','手机号','姓名','入职日期',.......]
      // 1 生成表头
      // tHeader  ---> ['转正日期', '部门', '聘用形式', '编号', '手机号', '密码', '头像地址', '入职日期', '姓名', '工号']
      const one = userList[0]
      if (!one) return
      const tHeader = Object.keys(one).map(en_key => {
        return mapInfo[en_key]
      })
      console.log(tHeader, 'tHeader')
      // 2 生成表的内容data
      const result = userList.map(item => {
        return Object.values(item)
      })

      console.log(result, 'data')
      return { tHeader, result }
    },
    // 删除数据
    doDel(id) {
      this.$confirm('确定要删除此数据吗').then(async() => {
        const { data } = await delUser(id)
        console.log(data)
        this.$message.success(data.message)
        if (this.userList.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadUserList()
      })
    },
    // 关闭弹框，清空表单数据
    doClose() {
      this.$refs.myDialog.resetForm()
    },
    // 格式化聘用形式数据
    formatHireType(value) {
      return hireType[value] || '未知'
    },
    // 添加员工
    doAdd() {
      this.showDialog = false
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.loadUserList()
    },
    // 获取员工列表（渲染页面）
    async loadUserList() {
      const { data } = await getEmployeeList(this.page, this.size)
      console.log(data)
      this.userList = data.data.rows
      this.total = data.data.total
    },
    // 更改每页条数
    handleSizeChange(val) {
      this.size = val
      this.loadUserList()
    },
    // 更改页码
    handleCurrentChange(val) {
      this.page = val
      this.loadUserList()
    }
  }
}
</script>
